package com.kfm.bootdemo.filter;

import com.kfm.bootdemo.util.Constant;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

// 告诉 SpringBoot 来找我
// @Component
// @WebFilter("/*")
public class StudentFilter implements Filter {
    // 放行的资源
    // 登录注册的请求
    private static final List<String> ALLOW_PATH = List.of("/", "/login", "/captcha", "/register");
    // 静态资源
    private static final String[] RESOURCES = {"/css", "/js", "/imgs", "/fonts", "/favicon.ico"};
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String path = request.getContextPath(); // 上下文路径 /boot
        String url = request.getRequestURI(); // 本次请求的字符串 /boot/login
        url = url.substring(path.length()); // /css/login.css /js/bootstrap.js /font/jet.  /img/logo.png
        System.out.println(url);
        if (ALLOW_PATH.contains(url)) {
            // 说明是登录或者注册的请求，放行
            System.out.println("登录或者注册，放行");
            filterChain.doFilter(request, response);
            return;
        }
        for (String resource : RESOURCES) {
            if (url.startsWith(resource)) {
                // 说明请求的是静态资源，放行
                System.out.println("静态资源，放行");
                filterChain.doFilter(request, response);
                return;
            }
        }

        // 判断是否登录
        Object user = request.getSession().getAttribute(Constant.LOGIN_USER_KEY);
        if (user == null) {
            // 没有登录
            System.out.println("你还没有登录，不放行");
            response.sendRedirect("/login");
            return;
        }
        filterChain.doFilter(request, response);
    }
}
